<template>
  <div class="combination-add-chunk4">
    <div class="head">
      <div class="h-title">回测参数</div>
      <div class="h-body">
        <el-form ref="dataForm" :inline="true" label-width="70px" :model="dataForm" class="el-form-center">
          <el-form-item label="回测区间" prop="">
            <el-date-picker
              v-model="dataForm.startTime"
              type="date"
              size="mini"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions1"
              placeholder="选择日期"
              style="width: 160px;">
            </el-date-picker>
            ~
            <el-date-picker
              v-model="dataForm.endTime"
              type="date"
              size="mini"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions2"
              placeholder="选择日期"
              style="width: 160px;">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="业绩基准" label-width="80px" prop="strategyName">
            <indexSelectTree
              style="margin: 0 30px 0 10px"
              :indexType.sync="dataForm.types"
              :clearable="false"
              :width="280"
            ></indexSelectTree>
          </el-form-item>
        </el-form>
        <el-button style="height: 28px;" type="primary" @click="saveHandle" size="mini">应用</el-button>
      </div>
    </div>
    <div class="card1">
      <div class="chunk chunk1-1">
        <div class="title">业绩概览</div>
        <chart1 v-if="list_netWorthLine.length&&Object.keys(contrastIndex_obj).length" id="combinationChunk4Chart1" :data="list_netWorthLine" :contrastIndex_obj="contrastIndex_obj" :key="chart1_key" height="350px" width="100%" />
      </div>
      <div class="chunk chunk1-2">
        <div class="title">收益风险指标</div>
        <el-table
          v-loading="listLoading_riskIndicators"
          :data="list_riskIndicators"
          fit
          size="mini"
          style="width: 100%;margin-top:20px"
          :cell-style="{padding: '8px 0'}"
          :header-cell-style="{background:'#dcedff',color:'#32639d'}"
        >
          <el-table-column type="index" width="100" :index="titleHandle"></el-table-column>
          <el-table-column :prop="key" :label="add_column_list[key]" v-for="(item, key) in list_riskIndicators[0]" :key="key" align="center"></el-table-column>
        </el-table>
      </div>
    </div>
    <div class="card2">
      <div class="title">历史月度表现</div>
      <div class="line" style="margin-top: 10px;">
        <div class="showMonth">
          <div class="round round1"></div>
          组合方案
        </div>
        <div class="showMonth">
          <div class="round round2"></div>
          <el-select style="width: 130px;" v-model="month_contrast" size="mini" placeholder="请选择" @change="monthContrastHandle">
            <el-option
              v-for="item in one_contrastOptions_list"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
      </div>
      <el-table
        v-loading="listLoading_monthNetWorth"
        :data="list_showMonth"
        stripe fit
        size="mini"
        :cell-class-name="showMonthTableClassName"
        :cell-style="{padding: '8px 0'}"
        :header-cell-style="{background:'#dcedff',color:'#32639d'}"
        style="width: 100%;margin-top:15px"
      >
        <el-table-column prop="0.year" label="年份" width="100" align="center"></el-table-column>
        <el-table-column :prop="`${i-1+''}`" :label="`${i}月`" align="center" v-for="i in 12" :key="i">
          <template slot-scope="scope">
            <span v-if="scope.row[i-1].monthIncrease!=null" :class="scope.row[i-1].monthIncrease>=0?'positiveFc':'negativeFc'">
              {{scope.row[i-1].monthIncrease}}%
            </span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="12.monthIncrease" label="YTD" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row[12].monthIncrease!=null" :class="scope.row[12].monthIncrease>=0?'positiveFc':'negativeFc'">
              {{scope.row[12].monthIncrease}}%
            </span>
            <span v-else>--</span>
          </template>
        </el-table-column>
      </el-table>
      <div class="line" style="margin-top: 20px;">
        <el-button-group>
          <el-button size="small" :type="monthChartBtn?'':'primary'" @click="monthChartBtn=0">月度回报</el-button>
          <el-button size="small" :type="monthChartBtn?'primary':''" @click="monthChartBtn=1">收益分布</el-button>
        </el-button-group>
      </div>
      <div class="month-chartContent">
        <div class="mChunk">
          <showmonth-chart v-if="monthChartBtn" id="combinationChunk4ShowmonthChart" :name_contrast="name_contrast" :month_contrast="month_contrast" y-name="组合策略" :data="list_monthNetWorthLine" height="350px" width="100%" />
          <month-return-chart v-else-if="!monthChartBtn" id="combinationChunk4MonthReturnChart" :name_contrast="name_contrast" :month_contrast="month_contrast" y-name="组合策略" :data="list_monthNetWorthDistributed" :height="400" width="100%" />
        </div>
        <div class="mChunk">
          <el-table
            v-show="monthChartBtn"
            v-loading="findNetWorthExtendByStrategyId2_loading"
            :data="list_showMonth_profit"
            stripe fit
            size="mini"
            :cell-style="{padding: '6px 0'}"
            :header-cell-style="{background:'#dcedff',color:'#32639d'}"
            style="width: 100%;margin-top:20px"
            :key="list_showMonth_key"
          >
            <el-table-column prop="" label="" align="center">
              <template slot-scope="scope">
                <span>{{list_showMonth_profit_column1[scope.$index].name}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="1" label="策略组合" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.incomMonthValue" :class="scope.row.incomMonthValue>0?'positiveFc':'negativeFc'">{{ scope.row.incomMonthValue }}%</span>
                <span v-else>--</span>
              </template>
            </el-table-column>
            <el-table-column prop="2" :label="name_contrast" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.growth" :class="scope.row.growth>0?'positiveFc':'negativeFc'">{{ scope.row.growth }}%</span>
                <span v-else>--</span>
              </template>
            </el-table-column>
          </el-table>
          <el-table
            v-show="!monthChartBtn"
            v-loading="getMonthNetWorthDetial_loading"
            :data="list_table_getMonthNetWorthDetial"
            stripe fit
            size="mini"
            :cell-style="{padding: '6px 0'}"
            :header-cell-style="{background:'#dcedff',color:'#32639d'}"
            style="width: 100%;margin-top:20px"
          >
            <el-table-column prop="date" label="净值日期" align="center"></el-table-column>
            <el-table-column prop="netWorthMonth" label="单位净值" align="center"></el-table-column>
            <el-table-column prop="netWorthRestorationMonth" label="累计净值" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.netWorthRestorationMonth"><span style="color:#F00;">*</span>{{ scope.row.netWorthRestorationMonth }}</span>
                <span v-else>--</span>
              </template>
            </el-table-column>
            <el-table-column prop="monthIncrease" label="月涨跌幅" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.monthIncrease" :class="scope.row.monthIncrease>0?'positiveFc':'negativeFc'">{{ scope.row.monthIncrease }}%</span>
                <span v-else>--</span>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="monthNetWorthDetial_total>0&&(!monthChartBtn)" style="padding-bottom: 0;"
            :total="monthNetWorthDetial_total"
            :page.sync="monthNetWorthDetial_listQuery.pageCurrent"
            :limit.sync="monthNetWorthDetial_listQuery.limit" @pagination="getMonthNetWorthDetial"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { parseTime, deepClone } from '@/utils'
import chart1 from '@/components/Charts/combination_add_chunk4_1.vue'
import { queryAllIndexType, getMonthlyIndex, findIndexByIndexTypeAndIndexTime, netWorthLine, riskIndicators, getIndexRiskByIndexTypeAndTime, getMonthNetWorth,
  getMonthNetWorthDistributed, getMonthNetWorthDetial, getMonthNetWorthLine, findNetWorthExtendByStrategyId2, findTimeScopeGrowth } from '@/api/policyManage'
import showmonthChart from '@/components/Charts/lineEcharts_netWorthShowMonth.vue'
import monthReturnChart from '@/components/Charts/barEcharts_monthReturn.vue'
import Pagination from '@/components/Pagination'
import indexSelectTree from "@/components/investComn/indexSelectTree.vue";

export default {
  components: { chart1, showmonthChart, monthReturnChart, Pagination,indexSelectTree },
  props: {
    base_contrast: {
      type: Number,
      default: 9
    },
    strategyId: {
      type: Number,
      default: undefined
    },
    userId: {
      type: String | Number,
      required: true
    },
    startTime: {
      type: String,
      required: true
    },
  },
  data() {
    var vue = this
    return {
      contrastOptions: [], // 业绩基准 原数据
      contrastOptions_obj: [], // 字典数据

      dataForm: {
        types: [],
        startTime: null,
        endTime: parseTime(new Date())
      },
      enterTime: null,
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() < new Date(vue.startTime).getTime()-60*60*24*1000
        }
      },
      pickerOptions2: {
        disabledDate(time) {
          // return Date.now()-60*60*24*1*1000 > time.getTime() || time.getTime() > Date.now()
          return time.getTime() > Date.now()
        }
      },

      // 业绩概览
      list_netWorthLine: [],
      chart1_key: 1,

      // 收益风险指标
      riskIndicators_columnLabel: {
        'annualizedIncomeRate': '年化收益',
        'annualFluctuationsRate': '年化波动',
        'sharpeRate': '夏普比率',
        'maximumDrawdownRate': '最大回撤',
        'calmarRate': '卡玛比率',
        'maxBackIncomDay': '最大回补天数'
      },
      listLoading_riskIndicators: false,
      list_riskIndicators: [],
      _list_riskIndicators: [],
      one_contrastOptions_list: [], // 对比选择条目
      month_contrast: undefined, // 对比选择结果
      contrastIndex_obj: {}, // 业绩概览 对比指标数据
      add_column_list: [],

      // 历史月度表现
      listLoading_monthNetWorth: false,
      list_showMonth: [],
      _list_showMonth: [],
      monthChartBtn: 0,
      findNetWorthExtendByStrategyId2_loading: false,
      getMonthNetWorthDetial_loading: false,
      list_showMonth_profit: [], // 收益分布 列表
      list_table_getMonthNetWorthDetial: [], // 月度回报 列表
      list_showMonth_key: 0,
      list_showMonth_profit_column1: [
        { id: 99, name: '成立以来' },
        { id: 0, name: '今年以来' },
        { id: 1, name: '近1月' },
        { id: 3, name: '近3月' },
        { id: 6, name: '近6月' },
        { id: 12, name: '近1年' },
        { id: 24, name: '近2年' },
        { id: 36, name: '近3年' },
      ],
      name_contrast: '',
      list_monthNetWorthLine: [], // 收益分布 图表
      list_monthNetWorthDistributed: [], // 月度回报 图表
      monthNetWorthDetial_listQuery: { // 月度回报 分页
        pageCurrent: 1,
        limit: 10
      },
      monthNetWorthDetial_total: 0,
    }
  },
  watch: {
    'dataForm.startTime': {
      handler(val) {
        console.log(val)
      }
    },
    'dataForm.types': {
      handler(newVal, oldVal) {
        if(newVal.length > 4) {
          this.$notify({
            message: '最多选择4个对比指标',
            type: 'warning',
            duration: 2000
          })
          this.$nextTick(() => {
            this.formData.types = oldVal
          })
        }else {
          if(Object.keys(this.contrastOptions_obj).length) {
            this.one_contrastOptions_list = []
            newVal.forEach(item => {
              this.one_contrastOptions_list.push({
                id: item,
                name: this.contrastOptions_obj[item]
              })
            })
            this.month_contrast = newVal[0]
            // this.monthContrastHandle(newVal[0])
          }
        }
      },
      deep: true
    },
    month_contrast(val) {
      if(val) {
        this.name_contrast = this.contrastOptions_obj[val] // 月度表现头部修改
      }
    },
  },
  created() {
    this.dataForm.startTime = this.startTime
    Promise.all([this.queryAllIndexType()/*对比指标 选择树*/]).then(res => {
      this.netWorthLine() // 业绩概况曲线
    })

    this.getriskIndicators()
    this.getMonthNetWorth()
    this.getMonthNetWorthDetial()
    this.getMonthNetWorthDistributed() // 月度回报 图表
    this.getMonthNetWorthLine() // 收益分布 图表
    // setTimeout(() => {
    //   this.getIndexRiskByIndexTypeAndTime([this.base_contrast])
    // }, 500)
  },
  methods: {
    titleHandle(i) {
      const key_list = Object.keys(this.riskIndicators_columnLabel)
      return this.riskIndicators_columnLabel[key_list[i]]
    },
    showMonthTableClassName({ rowIndex, columnIndex }) {
      if(columnIndex === 0 && rowIndex%2 === 0) {
        return 'showMonthyearBorder0'
      }else if(columnIndex === 0 && rowIndex%2 !== 0) {
        return 'showMonthyearBorder1'
      }
    },
    // 对比指标 选择树
    queryAllIndexType() {
      return new Promise(reject => {
        queryAllIndexType().then(res => {
          console.log('对比指标', res)
          res.body.forEach((item, i) => {
            res.body[i].typeName = item.modelName
          })
          this.contrastOptions = res.body
          res.body.forEach(items => {
            items.lists.forEach(item => {
              this.contrastOptions_obj[item.id] = item.typeName
            })
          })
          this.dataForm.types.forEach(item => {
            this.one_contrastOptions_list.push({
              id: item,
              name: this.contrastOptions_obj[item]
            })
          })
          this.dataForm.types.push(this.base_contrast)
          this.month_contrast = this.dataForm.types[0]
          // this.monthContrastHandle(this.month_contrast)
          reject()
        })
      })
    },
    // 业绩概览
    netWorthLine() {
      netWorthLine({
        userId: this.userId,
        strategyId: this.strategyId,
        startDate: this.dataForm.startTime,
        endDate: this.dataForm.endTime,
      }).then(res => {
        console.log('业绩概览', res)
        this.list_netWorthLine = res.body
        const enterTime = res.body[res.body.length-1].networthTime
        this.$emit('enterTime', enterTime)
        this.enterTime = enterTime
        this.findIndexByIndexTypeAndIndexTime(this.dataForm.startTime, enterTime, this.dataForm.types)
        this.findNetWorthExtendByStrategyId2() // 收益分布 列表 -- 收益分布 列表 对比指数
        this.monthContrastHandle(this.month_contrast)
        this.getIndexRiskByIndexTypeAndTime([this.base_contrast])
      })
    },
    // 业绩概览 对比指标
    findIndexByIndexTypeAndIndexTime(startTime, endTime, indexType) {
      findIndexByIndexTypeAndIndexTime({
        startTime,
        endTime,
        indexType
      }).then(res => {
        console.log('业绩概览 对比指标', res)
        this.contrastIndex_obj = {}
        Object.keys(res.body).forEach(key => {
          const item = res.body[key]
          const _key = this.contrastOptions_obj[key]
          this.contrastIndex_obj[_key] = item
        })
        this.chart1_key++
      })
    },
    // 收益风险指标
    getriskIndicators() {
      riskIndicators({
        strategyId: this.strategyId
      }).then(res => {
        this.listLoading_riskIndicators = false
        console.log('收益风险指标', res)
        this.add_column_list.push('组合方案')
        Object.keys(this.riskIndicators_columnLabel).forEach((key, i) => {
          const val = res.body[key]
          this.list_riskIndicators[i] = {}
          this.list_riskIndicators[i]['0'] = val
        })
        this._list_riskIndicators = deepClone(this.list_riskIndicators)
      })
    },
    // 收益风险指标 对比指标
    getIndexRiskByIndexTypeAndTime(indexType) {
      getIndexRiskByIndexTypeAndTime({
        indexType,
        startTime: this.dataForm.startTime,
        endTime: this.enterTime,
      }).then(res => {
        console.log('收益风险指标 对比指标', res)
        const key_list = ['annualizedIncomeRate', 'annualFluctuationsRate', 'sharpeRate', 'maximumDrawdownRate', 'calmarRate', 'maxBackIncomDay']
        const obj = res.body
        this.add_column_list = this.add_column_list.slice(0, 1)
        this.list_riskIndicators = deepClone(this._list_riskIndicators)
        Object.keys(obj).forEach(key => {
          const element = obj[key]
          const header = this.contrastOptions_obj[key]
          this.list_riskIndicators.forEach((item, i) => {
            const index = Object.keys(item).length
            if(index!==0) {
              item[index] = element[key_list[i]]
            }else {
              item[1] = element[key_list[i]]
            }
          })
          this.add_column_list.push(header)
        })
      })
    },
    // 历史月度表现
    getMonthNetWorth() {
      this.listLoading_monthNetWorth = true
      getMonthNetWorth({
        strategyId: this.strategyId
      }).then(res => {
        this.listLoading_monthNetWorth = false
        const list = Object.keys(res.body).map(function(i) { return res.body[i] })
        const new_list = deepClone(list)
        console.log('历史月度表现', list)
        list.forEach((items, index) => {
          if(items.length<13) {
            new_list[index] = []
            const year = items[0].year
            for(let i=0; i<13; i++) {
              if(items[i]&&items[i].month != i+1) {
                if(!new_list[index][i]) {
                  new_list[index][i] = {
                    year: items[i].year
                  }
                }
                new_list[index][items[i].month-1] = deepClone(items[i])
              }else if(!new_list[index][i]) {
                if(items[i]&&items[i].month == i+1) {
                  new_list[index][items[i].month-1] = deepClone(items[i])
                }else {
                  new_list[index][i] = {
                    year
                  }
                }
              }
            }
          }
        })
        this.list_showMonth = new_list
        this._list_showMonth = deepClone(new_list)
        console.log('历史月度表现 修改........', this.list_showMonth)
      })
    },
    // 历史月度表现 对比指数
    monthContrastHandle(indexType) {
      getMonthlyIndex({
        indexType,
        startTime: this.dataForm.startTime,
        endTime: this.enterTime,
      }).then(res => {
        console.log('历史月度表现 对比指数', res)
        Object.keys(res.body).forEach(key => {
          const items = res.body[key]
          items.forEach(item => {
            if(item.indexTime) {
              item.month = Number(item.indexTime.slice(5))
            }else {
              item.month = 13
            }
            item.monthIncrease = item.indexGrowthRate==null ? null : Number(item.indexGrowthRate)
          })
        })
        const list = Object.keys(res.body).map(function(i) { return res.body[i] })
        const new_list = deepClone(list)
        list.forEach((items, index) => {
          if(items.length<13) {
            new_list[index] = []
            const year = items[0].year
            for(let i=0; i<13; i++) {
              if(items[i]&&items[i].month != i+1) {
                if(!new_list[index][i]) {
                  new_list[index][i] = {
                    year: items[i].year
                  }
                }
                new_list[index][items[i].month-1] = deepClone(items[i])
              }else if(!new_list[index][i]) {
                if(items[i]&&items[i].month == i+1) {
                  new_list[index][items[i].month-1] = deepClone(items[i])
                }else {
                  new_list[index][i] = {
                    year
                  }
                }
              }
            }
          }
        })
        this.list_showMonth = deepClone(this._list_showMonth)
        new_list.forEach(element => {
          this.list_showMonth.forEach((item, i) => {
            if(element[0].year == item[0].year) {
              this.list_showMonth.splice(i+1, 0, element)
            }
          })
        })
        if(this.month_contrast) this.findTimeScopeGrowth(this.month_contrast)
      })
    },
    // 收益分布
    getMonthNetWorthLine() {
      getMonthNetWorthLine({
        strategyId: this.strategyId
      }).then(res => {
        console.log('收益分布', res)
        this.list_monthNetWorthLine = res.body
      })
    },
    headTail(list) {
      list.unshift(list[list.length-1])
      list.splice(list.length-1, 1)
    },
    // 收益分布 列表
    findNetWorthExtendByStrategyId2() {
      this.findNetWorthExtendByStrategyId2_loading = true
      findNetWorthExtendByStrategyId2({
        strategyId: this.strategyId
      }).then(res => {
        console.log('收益分布 列表', res)
        this.headTail(res.body)
        this.list_showMonth_profit = res.body
        this.findTimeScopeGrowth(this.month_contrast)
      })
    },
    // 收益分布 列表 对比指数
    findTimeScopeGrowth(indexType) {
      findTimeScopeGrowth({
        indexType,
        startTime: this.dataForm.startTime,
        endTime: this.enterTime,
      }).then(res => {
        console.log('收益分布 对比指数', res)
        this.headTail(res.body)
        this.findNetWorthExtendByStrategyId2_loading = false
        this.list_showMonth_profit.forEach((item, i) => {
          item.growth = res.body[i].growth
        })
        this.list_showMonth_key++
      })
    },
    // 月度回报
    getMonthNetWorthDistributed() {
      getMonthNetWorthDistributed({
        strategyId: this.strategyId
      }).then(res => {
        console.log('月度回报', res)
        this.list_monthNetWorthDistributed = res.body
      })
    },
    // 月度回报 列表
    getMonthNetWorthDetial() {
      this.getMonthNetWorthDetial_loading = true
      getMonthNetWorthDetial({
        strategyId: this.strategyId,
        ...this.monthNetWorthDetial_listQuery
      }).then(res => {
        console.log('月度回报 列表', res)
        this.getMonthNetWorthDetial_loading = false
        this.list_table_getMonthNetWorthDetial = res.body
        this.monthNetWorthDetial_total = res.count
      })
    },
    saveHandle() {
      this.monthContrastHandle(this.dataForm.types[0])
      this.getIndexRiskByIndexTypeAndTime(this.dataForm.types)
      this.netWorthLine()
    }
  }
}
</script>

<style lang="scss" scoped>
.combination-add-chunk4 {
  .head {
    border: 1px solid #ccc;
    .h-title {
      padding: 0 10px;
      line-height: 35px;
      display: flex;
      justify-content: space-between;
      background: #f1f0f0;
      border-bottom: 1px solid #ccc;
    }
    .h-body {
      padding: 10px;
      display: flex;
      justify-content: space-between;
      align-content: center;
    }
  }
  .title {
    display: flex;
    align-items: center;
    &::before {
      display: inline-block;
      content: '';
      width: 4px;
      height: 20px;
      background: #42b983;
      margin-right: 6px;
    }
  }
  .card1 {
    display: flex;
    margin-top: 20px;
    .chunk1-1 { width: 65%; }
    .chunk1-2 { width: 35%; }
  }
  .card2 {
    margin-top: 20px;
    .line {
      display: flex;
      .showMonth {
        display: flex;
        align-items: center;
        & + .showMonth {margin-left: 15px;}
        .round {width: 10px;height: 10px;border-radius: 50%;margin-right: 5px;}
        .round1 {background: #e16757;}
        .round2 {background: #78b2eb;}
      }
    }
    .month-chartContent {
      display: flex;
      .mChunk {flex: 1;}
    }
  }
}
</style>

